<template>
    <el-card shadow="never">
        <detail-header :query="queryStore" />
    </el-card>
    <!-- 销售统计 || 推广活动统计 -->
    <div v-if="['3', '6'].includes(queryStore.source)" class="tab-title">
        <div
            class="tab-title-item"
            :class="{ 'item-active': statisticsName == 'salesStatistics' }"
            @click="handleChange('salesStatistics')">
            销售统计
        </div>
        <!-- 3-> 淘宝  6-> 天猫 -->
        <div
            class="tab-title-item"
            :class="{ 'item-active': statisticsName == 'promotionStatistics' }"
            @click="handleChange('promotionStatistics')">
            推广活动统计
        </div>
    </div>
    <div v-if="statisticsName == 'salesStatistics'" class="statistics-card">
        <DataOverview />
        <PaymentTop />
    </div>
    <!-- ================ 销售统计 of start ================ -->
    <!-- <div v-show="statisticsName == 'salesStatistics'">

        <Converse v-if="[1, 4].includes(source)" ref="ConverseRef" />
        <div class="tab_box" :style="{ gridTemplateColumns: `repeat(${[1, 4].includes(source) ? 2 : 1}, 1fr)` }">
            <FunnelChart v-if="[1, 4].includes(source)" ref="OrderFunnelChartRef" v-loading="tradingLoading" />
            <FunnelChart ref="CustFunnelChartRef" v-loading="tradingLoading" />
        </div>
        <div class="tab_box" :style="{ gridTemplateColumns: `repeat(${![3, 6].includes(source) ? 2 : 1}, 1fr)` }">
            <ProductTable
                v-if="![3, 6].includes(source)"
                ref="ProductTableRef"
                v-loading="productTopLoading"
                @export="onExport" />
            <ProductTable ref="OrderTableRef" v-loading="productTopLoading" @export="onExport" />
        </div>
        <template v-if="![3, 6].includes(source)">
            <div v-loading="salesLoading" class="tab_box">
                <StoreTable ref="StoreTableTopRef" @export="onExport" />
                <StoreTable ref="StoreTableLastRef" @export="onExport" />
            </div>
        </template>
    </div> -->
    <!-- ================ 销售统计 of end ================ -->
    <!-- ================ 推广活动统计 of start ================ -->
    <!-- eslint-disable-next-line prettier/prettier -->
    <div
        v-if="statisticsName == 'promotionStatistics' && ['3', '6'].includes(queryStore.source)"
        class="statistics-card">
        <el-card shadow="never" class="statistics_container">
            <PromotionStatistics ref="PromotionStatisticsRef" />
        </el-card>
        <PromotionalActivityDetails></PromotionalActivityDetails>
    </div>
    <!-- ================ 推广活动统计 of end ================ -->
</template>
<script lang="ts" setup>
import Quantity from './components/Quantity.vue';
import Statistics from './components/Statistics.vue';
import Converse from './components/Converse.vue';
import FunnelChart from './components/FunnelChart.vue';
import ProductTable from './components/ProductTable.vue';
import StoreTable from './components/StoreTable.vue';

import DataOverview from '@/view/ecommerce/components/statistics/DataOverview.vue';
import PaymentTop from '@/view/ecommerce/components/statistics/PaymentTop.vue';

import { calendarChangefunc, disabledDateFunc, visibleChange } from './components/utils';

import PromotionalActivityDetails from './components/PromotionalActivityDetails/index.vue';

import { downFile, timeSlotChange } from '@/utils/utils';
import { ref, reactive, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { useRoute } from 'vue-router';
import lodash from 'lodash';
import {
    getStoreList,
    getTotleData,
    getTrendAnalysis,
    getConverse,
    getTradingConverse,
    getProductTop,
    getSales
} from '@/api/ecommerce/storeManage';
import detailHeader from '../components/detailHeader.vue';
import search from '../components/search.vue';
import totleData from '../components/totleData.vue';
import converseData from '../components/converseData.vue';
import salesData from '../components/salesData.vue';
import StatisticsSearch from '@/components/zw/statistics-search/StatisticsSearch.vue';
import PromotionStatistics from './components/PromotionStatistics/index.vue';

const routers = useRoute();
const ConverseRef = ref<any>(null);
const OrderFunnelChartRef = ref<any>(null);
const CustFunnelChartRef = ref<any>(null);
const ProductTableRef = ref<any>(null);
const OrderTableRef = ref<any>(null);
const PromotionStatisticsRef = ref<any>(null);
const StatisticsSearchRef = ref<any>(null);

const StoreTableTopRef = ref<any>(null);
const StoreTableLastRef = ref<any>(null);
let queryStore = reactive<any>({});
const paramsData = ref<any>({});
const source = Number(routers.query.source);
/** ===================销售统计 和 推广活动统计 ================== */
const quantityLoading = ref(false);
const statisticsLoading = ref(false);
const productTopLoading = ref(false);
const tradingLoading = ref(false);
const salesLoading = ref(false);
const statisticsName = ref('salesStatistics');
interface Props {
    modelValue: string;
}
const props = withDefaults(defineProps<Props>(), {
    modelValue: ''
});
const emit = defineEmits(['update:modelValue']);
const QuantityRef = ref<any>(null);
const StatisticsRef = ref<any>(null);

const statisOptions = reactive([
    {
        label: '时间筛选',
        type: 'dateFilterTwo',
        currentId: 1,
        format: 'YYYY-MM-DD',
        disabledDate: disabledDateFunc,
        calendarChange: calendarChangefunc,
        visibleChange: visibleChange
    }
]);
const onSubmit = (data: any) => {
    // 如果是做了清空的操作，则不查询接口
    if (!data.times) {
        return;
    }
    nextTick(() => {
        const p = {
            date_type: data.currentId + 1,
            shop_id: [queryStore.shop_id],
            date: data.times || timeSlotChange('本周')
        };
        searchData(p);
    });
};

/**
 * 获取销售统计数据
 */
const searchData = async (params: any) => {
    paramsData.value = params;
    const params2 = lodash.cloneDeep(params);
    params2['source'] = 2;
    getTotalDataFunc(params);
    getTrendAnalysisFunc(params2);
    getTradingConverseFunc(params2);
    getProductTopFunc(params2);
    getConverseFunc(params);
    if ([3, 6].includes(source)) {
    } else {
        getSalesfunc(params);
    }
};

// ============================ 数据概览 of start ============================
const getTotalDataFunc = async (params: any) => {
    quantityLoading.value = true;
    const dataOverviewData = await getTotleData(params);
    // source 1-客易达  2-有赞 3-淘宝 4-自营 5-线下门店 6 天猫 7 抖店
    QuantityRef.value.onQuantity(dataOverviewData, source);
    quantityLoading.value = false;
};
// ============================ 数据概览 of end ============================

// ============================ 趋势图 of start ============================
const getTrendAnalysisFunc = async (params: any) => {
    statisticsLoading.value = true;
    const analData = await getTrendAnalysis(params);
    StatisticsRef.value.onStatistics(analData);
    statisticsLoading.value = false;
};
// ============================ 趋势图 of end ============================

// ============================ 客户转化 of start ============================
const getTradingConverseFunc = async (params: any) => {
    tradingLoading.value = true;
    const custData = await getTradingConverse(params);
    tradingLoading.value = false;
    if ([3, 6].includes(source)) {
        CustFunnelChartRef.value.onFunnelChart(custData?.cust_converse_list, 2, source);
    } else {
        if ([1, 4].includes(source)) {
            // 漏斗图
            OrderFunnelChartRef.value.onFunnelChart(custData.trade_converse_list, 1);
        }
        CustFunnelChartRef.value.onFunnelChart(custData.cust_converse_list, 2, source);
    }
};
// ============================ 客户转化 of end ============================

// ============================ 成交商品TOP10 of start ============================
const getProductTopFunc = async (params: any) => {
    productTopLoading.value = true;
    const topData = await getProductTop(params);
    productTopLoading.value = false;
    if ([3, 6].includes(source)) {
        OrderTableRef.value.onTable(topData.order_success_list, 2, source);
    } else {
        // 订单表格
        ProductTableRef.value.onTable(topData.purchased_list_top, 1);
        OrderTableRef.value.onTable(topData.order_success_list, 2);
    }
};
// ============================ 成交商品TOP10 of end ============================

// ============================ 转化 of start ============================
const getConverseFunc = async (params: any) => {
    if ([1, 4].includes(source)) {
        tradingLoading.value = true;
        const converData = await getConverse(params);
        // 转化
        ConverseRef.value.onConverse(converData);
        tradingLoading.value = false;
    }
};
// ============================ 转化 of end ============================

const getSalesfunc = async (params: any) => {
    // 门店表格
    salesLoading.value = true;
    const storeData = await getSales(params);
    salesLoading.value = false;
    StoreTableTopRef.value.onTable(storeData.stores_sales_top, 3);
    StoreTableLastRef.value.onTable(storeData.stores_sales_last, 4);
};

const onExport = (type: any) => {
    getSales({ ...paramsData.value, type }).then((res: any) => {
        // console.log('导出', res);
        downFile(res.url, res.url.split('/').pop());
    });
};

// 切换 tab 事件
const handleChange = (name: any) => {
    statisticsName.value = name;
    if (name == 'promotionStatistics') {
        PromotionStatisticsRef.value?.onSubmit();
    } else {
        StatisticsSearchRef.value?.onLoad();
    }
};

watch(
    () => routers.query,
    (val: any) => {
        // source  1-客易达  2-有赞 3-淘宝 4-自营 5-线下门店
        let { shop_id, name, source_name, source, logo, retail_shop_id } = val;
        shop_id = decodeURIComponent(shop_id);
        name = decodeURIComponent(name);
        source_name = decodeURIComponent(source_name);
        source = decodeURIComponent(source);
        logo = decodeURIComponent(logo);
        retail_shop_id = decodeURIComponent(retail_shop_id);
        queryStore = Object.assign({}, queryStore, { shop_id, name, source_name, source, logo, retail_shop_id });
    },
    { deep: true, immediate: true }
);
</script>
<style lang="scss" scoped>
@import './style/index';
</style>
